package me.zhengjie.modules.web.rest;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import freemarker.template.Configuration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.RateLimit;
import me.zhengjie.config.FileProperties;
import me.zhengjie.config.entity.ResponseBaseEntity;
import me.zhengjie.config.enums.AtmrErrorEnum;
import me.zhengjie.config.exception.WeChatException;
import me.zhengjie.config.word.util.WordCreateUtil;
import me.zhengjie.constant.ConstantUtils;
import me.zhengjie.enums.RedisKeyEnum;
import me.zhengjie.modules.system.domain.ExamResult;
import me.zhengjie.modules.system.domain.GroupTest;
import me.zhengjie.modules.system.domain.WxUser;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.service.mapstruct.ExamResultMapper;
import me.zhengjie.modules.utils.CreateExportHtmlUtil;
import me.zhengjie.modules.web.domain.AtmrListResponse;
import me.zhengjie.modules.web.domain.ExamResultSubmitRequest;
import me.zhengjie.modules.web.domain.VerifyFreeRequest;
import me.zhengjie.modules.web.domain.test.*;
import me.zhengjie.modules.web.service.IAtmrOrderService;
import me.zhengjie.modules.web.service.ICreateReportService;
import me.zhengjie.modules.web.service.ITestingService;
import me.zhengjie.modules.web.service.mybatisplus.IGroupTestPlusService;
import me.zhengjie.request.ATMRContext;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.SnowflakeIdWorker;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.http.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static me.zhengjie.enums.RedisKeyEnum.Enterprise;

/**
 * 测评管理
 */
@RestController
@RequestMapping("web/testing")
@Api(tags = "前端接口-测评")
@Slf4j
public class TestingController {

    @Value("${domain.url}")
    private String domainUrl;

    @Autowired
    private ITestingService testingService;

    @Autowired
    ICreateReportService createReportService;

    @Autowired
    WxUserService wxUserService;

    @Autowired
    ExamResultService examResultService;

    @Autowired
    ExamResultMapper examResultMapper;

    @Autowired
    Configuration freemarkerConfig;

    @Autowired
    FileProperties properties;

    @Autowired
    SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    ExamReportFtlService examReportFtlService;

    @Autowired
    ExamInfoService examInfoService;

    @Autowired
    AtmrService atmrService;

    @Autowired
    CreateExportHtmlUtil createExportHtmlUtil;

    @Autowired
    private IAtmrOrderService atmrOrderService;
    @Autowired
    AdvertService advertService;
    @Autowired
    private GroupTestService groupTestService;

    @Autowired
    DictDetailService dictDetailService;

    @Autowired
    WordCreateUtil wordCreateUtil;

    @Autowired
    ExamOrderService examOrderService;

    @Autowired
    UserFamilyMembersService userFamilyMembersService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private IGroupTestPlusService groupTestPlusService;

    /**
     * 根据测评ID查询详情
     *
     * @return
     */
    @PostMapping("getAtmrInfoById")
    @ApiOperation("WEB-根据测评ID查询详情")
    public ResponseBaseEntity queryAtmrInfoByAtmrId(@RequestBody QueryAtmrDetailRequest detailRequest) {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            String openId = ATMRContext.getContext().getOpenId();
            if (Objects.isNull(detailRequest.getAtmrId()) || StringUtils.isBlank(openId)) {
                throw new WeChatException("参数缺少");
            }
            AtmrDto atmrDto = atmrService.findById(detailRequest.getAtmrId());
            if (Objects.isNull(atmrDto)){
                throw new WeChatException("参数不合法");
            }
            ExamOrderDto examOrderDto = atmrOrderService.getPayedNoAnswerOrder(openId,String.valueOf(atmrDto.getId()));
            atmrDto.setExamOrderDto(examOrderDto);
            if (Objects.nonNull(detailRequest.getGroupTestId())){
                VerifyGroupTestRespDTO respDTO = testingService.verifyGroupTesting(detailRequest.getGroupTestId(),detailRequest.getGroupCode());
                if (respDTO.isCanBeUsed()){
                    atmrDto.setPrice(respDTO.getTestingPrice().stripTrailingZeros().toPlainString());
                    atmrDto.setReportPrice(respDTO.getReportPrice().stripTrailingZeros().toPlainString());
                }else {
                    atmrDto.setExceptionMsg(respDTO.getMsg());
                }
            }
            boolean checkResult = testingService.checkCompanyTesting(detailRequest.getEntCode());
            if (!checkResult){
                atmrDto.setExceptionMsg("该企业已禁止测评业务");
            }
            response.setBody(atmrDto);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    /**
     * 提测列表
     *
     * @return
     */
    @PostMapping("verifyFree")
    @ApiOperation("WEB-验证团体测试是否免费")
    public ResponseBaseEntity verifyFree(@RequestBody VerifyFreeRequest requestEntity) {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            if (null == requestEntity.getGroupId() || StringUtils.isBlank(requestEntity.getOpenId())) {
                //throw new WeChatException("参数缺少");
                response.setBody(false);
                return response;
            }
            //boolean result = testingService.verifyFree(requestEntity.getGroupId(),requestEntity.getOpenId());
            GroupTestDto result = atmrOrderService.verifyGroupTest(requestEntity.getGroupId(), requestEntity.getOpenId());
            response.setBody(result != null);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    /**
     * 提测列表
     *
     * @return
     */
    @PostMapping("list")
    @ApiOperation("WEB-测试管理列表")
    public ResponseBaseEntity list() {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            List<AtmrDto> list = testingService.list();
            response.setBody(list);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    /**
     * 提测单元列表
     * @return
     */
    @RequestMapping("unit")
    @RateLimit(value = 30.0, timeout = 500)
    public ResponseBaseEntity unit() {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            List<AtmrTestUnitRespDTO> list = testingService.unitList();
            response.setBody(list);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }
    /**
     * 提测B端企业列表
     * @return
     */
    @RequestMapping("company")
    @RateLimit(value = 30.0, timeout = 500)
    public ResponseBaseEntity company() {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            List<AtmrTestCompanyRespDTO> list = testingService.companyList();
            response.setBody(list);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    @RequestMapping("getTestResultByCode")
    @RateLimit(value = 100.0, timeout = 2000)
    public ResponseBaseEntity getTestResultByCode(@RequestBody AtmrTestResultReqDTO reqDTO) {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            List<AtmrTestResultRespDTO> list = testingService.getTestResultByCode(reqDTO);
            response.setBody(list);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    /**
     * 提测列表
     *
     * @return
     */
    @PostMapping("listNew")
    @ApiOperation("WEB-测试管理列表New")
    public ResponseBaseEntity listNew() {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            List<AtmrListResponse> list = testingService.listNew();
            response.setBody(list);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    /**
     * 提测
     *
     * @return
     */
    @PostMapping("getExamById")
    @ApiOperation("WEB-根据主键获取测试管理")
    public ResponseBaseEntity getExamById(@RequestParam Integer examId) {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            AtmrDto list = testingService.getExamById(examId);
            response.setBody(list);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    /**
     * 根据测试类型获取试题
     *
     * @return
     */
    @PostMapping("queryExamInfoByTypeId")
    @ApiOperation("WEB-根据测试类型获取试题")
    public ResponseBaseEntity queryExamInfoByTypeId(@RequestParam Integer atmrExamTypeId,@RequestParam Long examDatabaseId) {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            List<ExamInfoDto> list = examInfoService.createExamInfo(atmrExamTypeId,examDatabaseId);
            response.setBody(list);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    /**
     * 根据测试类型获取试题
     *
     * @return
     */
    @RequestMapping("queryExamInfoByAtmrId")
    @ApiOperation("WEB-根据测试类型获取试题-新")
    public ResponseBaseEntity queryExamInfoByAtmrId(@RequestParam Long atmrId) {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            List<ExamInfoDto> list = examInfoService.createExamInfoNew(atmrId);
            response.setBody(list);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    @GetMapping("getExamResult")
    @ApiOperation("获取用户测试结果详情")
    public ResponseBaseEntity getExamResult(@RequestParam Integer resultId) {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            if (ObjectUtil.isEmpty(resultId)) {
                return response;
            }
            ExamResultDto resultDto = examResultService.findById(resultId);
            if(StringUtils.isNotEmpty(resultDto.getOrderNo())){
                //resultDto.setExamOrder(examOrderService.findOne(resultId));
                resultDto.setHasPay(true);
            }
            AtmrDto atmrDto = atmrService.findById(Integer.parseInt(resultDto.getAtmrId()));
            resultDto.setReportPrice(atmrDto.getReportPrice());
            if (StringUtils.isNotBlank(resultDto.getGroupId())){
                GroupTest groupTest = groupTestPlusService.getById(resultDto.getGroupId());
                if (Objects.nonNull(groupTest)){
                    resultDto.setReportPrice(groupTest.getReportPrice());
                }
            }
            response.setBody(resultDto);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    /**
     * 获取用户测试结果列表
     *
     * @return
     */
    @GetMapping("queryExamResult")
    @ApiOperation("获取用户测试结果列表")
    public ResponseBaseEntity queryExamResult(@RequestParam String openId) {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            if (StringUtils.isBlank(openId)) {
                return response;
            }
            ExamResultQueryCriteria criteria = new ExamResultQueryCriteria();
            criteria.setWxId(openId);
            PageRequest page = PageRequest.of(0, Integer.MAX_VALUE, Sort.by(Sort.Order.desc("id")));
            Map<String, Object> pageImpl = examResultService.queryAll(criteria, page);
            List<ExamResultDto> list = (List<ExamResultDto>) pageImpl.get("content");
            if (CollectionUtils.isNotEmpty(list)) {
                for (ExamResultDto examResultDto : list) {
                    AtmrDto atmrDto = atmrService.findById(Integer.parseInt(examResultDto.getAtmrId()));
                    if (null != atmrDto) {
                        examResultDto.setAtmrName(atmrDto.getAtmrName());
                    }
                }
            }
            response.setBody(list);
        } catch (WeChatException e) {
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    @GetMapping("createReport")
    @ApiOperation("生成报告")
    public ResponseBaseEntity createReport(@RequestParam Integer resurltId){
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            ExamResultDto resultDto = examResultService.findById(resurltId);
            ExamResult examResult = JSONUtil.toBean(JSONUtil.toJsonStr(resultDto),ExamResult.class);
            String path = wordCreateUtil.createWord(examResult);
            response.setBody(path);
        }catch (Exception e){
            e.printStackTrace();
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    /**
     * 提测
     *
     * @return
     */
    @PostMapping("/submit")
    public ResponseBaseEntity submit(@RequestBody ExamResultSubmitRequest submitRequest) {
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            String openId = ATMRContext.getContext().getOpenId();
            if (StringUtils.isBlank(openId)) {
                throw new WeChatException("参数缺少");
            }
            submitRequest.setOpenId(openId);
            GroupTestDto groupTestDto = null;
            ExamResult er = new ExamResult();
            if ("".equals(submitRequest.getGroupId()) || submitRequest.getGroupId() == null || submitRequest.getGroupId().equals("null")) {
                er.setGroupId("0");//设置测试记录中的团体号
            } else {
                er.setGroupId(submitRequest.getGroupId());//设置测试记录中的团体号
                //校验是否符合团免条件
                //groupTestDto = atmrOrderService.verifyGroupTest(Integer.parseInt(submitRequest.getGroupId()), submitRequest.getOpenId());
            }
            AtmrDto atmrDto = atmrService.findById(Integer.valueOf(submitRequest.getAtmrId()));
            DictDetailDto dictDetailDto = dictDetailService.getDictByValue(atmrDto.getAtmrType());
            Map<String, Object> report = createReportService.create(submitRequest.getOpenId(),Integer.parseInt(submitRequest.getAtmrId()), submitRequest.getResult(), submitRequest.getExamContent());
            //report.put("result",submitRequest.getResult());
            if(!ObjectUtil.isEmpty(dictDetailDto)){
                report.put("reportType", dictDetailDto.getLabel());
            }
            er.setMemberId(submitRequest.getMemberId());
            er.setReportPrice(new BigDecimal(atmrDto.getReportPrice()));
            if(null != submitRequest.getMemberId()){
                UserFamilyMembersDto userFamilyMembersDto = userFamilyMembersService.findById(er.getMemberId());
                report.put("memberAge", userFamilyMembersDto.getMemberAge());
                report.put("memberSex", ConstantUtils.Order_Payed.equals(userFamilyMembersDto.getMemberSex())?"男":"女");
                report.put("memberName",userFamilyMembersDto.getUserName());
                DictDetailDto roleDetail = dictDetailService.getDictByValue(userFamilyMembersDto.getMemberRole());
                if(!ObjectUtil.isEmpty(roleDetail)){
                    report.put("memberRoleName",roleDetail.getLabel());
                }
            }

            String reportTezhi = report.get("reportTezhi").toString();
            if (reportTezhi != null && !"".equals(reportTezhi)) {
                er.setAtmrResultType(reportTezhi);
            }
            report.put("domainUrl", domainUrl);
            WxUser wxUser = wxUserService.findByOpenId(submitRequest.getOpenId());
            String name = StringUtils.defaultString(wxUser.getRealName(), wxUser.getNickname());
            if (StringUtils.isBlank(name)){
                name = "微信用户";
            }
            String syTeZhi = report.getOrDefault("syTezhi","").toString();
            er.setSyTeZhi(syTeZhi);//首要特质
            report.put("userName", name);//存入姓名
            report.put("mobile", wxUser.getMobile());//存入电话
            er.setWxId(submitRequest.getOpenId());
            er.setWxName(wxUser.getNickname());
            er.setWxRealName(wxUser.getRealName());
            er.setExamDatabaseId(submitRequest.getExamDatabaseId());
            er.setMobile(wxUser.getMobile());
            if ("0".equals(wxUser.getSex())) {
                er.setSex("女");
                report.put("sex", "女");//存入性别
            } else {
                er.setSex("男");
                report.put("sex", "男");//存入性别
            }
            //String title = TemplateEnum.getTemplate(er.getAtmrType(),atmrDto.getAgeType());
            report.put("resultTitle",atmrDto.getAtmrName());
            String examTime = DateUtil.localDateTimeFormat(DateUtil.toLocalDateTime(new Date()), "yyyy-MM-dd HH:mm:ss");
            er.setExamTime(examTime);
            er.setAtmrId(submitRequest.getAtmrId());
//            er.setExamResult(submitRequest.getResult());
            er.setExamResult(report.get("result").toString());
            er.setExamContent(submitRequest.getExamContent());
            er.setReportJson(JSONUtil.toJsonStr(report));
            er.setAtmrType(atmrDto.getAtmrType());
            er.setRelationship(submitRequest.getRelationship());
            er.setMemberName(submitRequest.getMemberName());
            String uuid = UUID.fastUUID().toString(true);
            report.put("UUID", uuid);
            er.setUuid(uuid);


            String url = wordCreateUtil.createWord(er);
            er.setReportUrl(url);
            er.setOrderNo(submitRequest.getOrderSn1());
            String entCode = submitRequest.getEntCode();
            er.setEntCode(entCode);
            if (StringUtils.isNotBlank(submitRequest.getEntCode()) && submitRequest.getEntCode().split("_").length > 1) {
                er.setCompanyCode(submitRequest.getEntCode().split("_")[0]);
                er.setEntCode(submitRequest.getEntCode().split("_")[1]);
                entCode = submitRequest.getEntCode().split("_")[1];
            }
            er.setGroupCode(submitRequest.getGroupCode());
            if (StringUtils.isNotBlank(submitRequest.getGroupCode())){
                BatchTestDetail testDetail = groupTestPlusService.getBatchDetailByCode(submitRequest.getGroupCode());
                er.setReportPrice(testDetail.getReportPrice());
                er.setGroupIndex(testDetail.getGroupIndex());
            }else {
                if (StringUtils.isNotBlank(submitRequest.getGroupId())){
                    BigDecimal reportPrice = groupTestPlusService.getReportPriceByGroupId(submitRequest.getGroupId());
                    er.setReportPrice(reportPrice);
                }
            }
            ExamResultDto resultDto = examResultService.create(er);
            resultDto.setReportPrice(atmrDto.getReportPrice());

            if (StringUtils.isBlank(wxUser.getPersonality()) && StringUtils.isNotBlank(reportTezhi)) {
                WxUser updateWxUser = new WxUser();
                updateWxUser.setId(wxUser.getId());
                updateWxUser.setPersonality(reportTezhi);
                wxUserService.update(updateWxUser);
            }
            String finalEntCode = entCode;
            ThreadUtil.execute(() -> {
                if (StringUtils.isNotBlank(submitRequest.getOrderSn()) || StringUtils.isNotBlank(submitRequest.getOrderSn1())) {
                    atmrOrderService.answerUpdate(submitRequest.getOpenId(), submitRequest.getOrderSn());
                    atmrOrderService.answerUpdate(submitRequest.getOpenId(), submitRequest.getOrderSn1());
                }
                testingService.setLockUser(wxUser,submitRequest.getGroupId());

                //同步企业测试参数
                if (StringUtils.isNotBlank(finalEntCode)) {
                    String syncUrl = "http://enterprise.drzh-atmr.cn/api/examResult/receive";
                    AtmrTestResultRespDTO resultRespDTO = new AtmrTestResultRespDTO();
                    resultRespDTO.setEntCode(finalEntCode);
                    resultRespDTO.setExamResult(er.getExamResult());
                    resultRespDTO.setAtmrResultType(er.getAtmrResultType());
                    String result = HttpUtils.post(syncUrl, JSON.toJSONString(resultRespDTO));
                    boolean cache = redisUtils.set(RedisKeyEnum.getEnterpriseKey(finalEntCode), resultRespDTO,Enterprise.getExpire());
                    log.info("同步企业测评结果:{},放入缓存结果:{}", result,cache);
                }
            });
            //同步更新团测数量
            /*if (null != groupTestDto) {
                GroupTest groupTest = new GroupTest();
                groupTest.setId(groupTestDto.getId());
                groupTest.setLimitUsed(groupTestDto.getLimitUsed() + 1);
                groupTestService.update(groupTest);
            }*/
            response.setBody(resultDto);
        } catch (WeChatException e) {
            e.printStackTrace();
            response.getHeader().setErrCode("-1");
            response.getHeader().setErrMsg(e.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            response.getHeader().setErrCode(AtmrErrorEnum.EC_ALL_99999.getErrorCode());
            response.getHeader().setErrMsg(AtmrErrorEnum.EC_ALL_99999.getErrorMessage());
        }
        return response;
    }

    /**
     * 提测
     *
     * @return
     */
    @PostMapping("/test")
    public ResponseBaseEntity test(String url, String uuid, String echart_pho) {
//        changeContent(url,url);
        ResponseBaseEntity response = new ResponseBaseEntity();
        try {
            ExamResult resources = examResultService.findByUuid(uuid);
            // /file/html/20211224/923935284276494336.html
            String reportUrl = resources.getReportUrl();
            String[] strAttr = reportUrl.split("\\.");
            String reportUrl2 = strAttr[0] + "_exp" + ".html";
            String filePath = properties.getPath().getPath()
                    + File.separator;
            filePath = filePath.substring(0, filePath.length() - 6);
            System.out.println("filePath " + filePath);
            changeContent(filePath + reportUrl, filePath + reportUrl2, echart_pho);
            resources.setEchart_pho(reportUrl2);
            examResultService.update(resources);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    private static void changeContent(String filePath, String savePath, String replaceStr) {
        // filePath 要读取的文件 savePath 要写入的文件

        BufferedReader br = null;

        BufferedWriter bw = null;

        try {
            // 以下读取和写入都转成UTF-8 防止乱码

            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));

            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(savePath), "UTF-8"));

            String line = null;

            while ((line = br.readLine()) != null && (line != "")) {
                bw.write(line.replaceAll("id='zhuImages'", "id='zhuImages' src='" + replaceStr + "'").replaceAll("id='atmr_zhu' style=\"width: 100%;height:400px;\"", "style=\"display:none\"")
                        .replaceAll("</body>", "</body><!--").replaceAll("</html>", "--></html>"));
            }

            bw.flush();

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                if (br != null) {
                    br.close();

                }

                if (bw != null) {
                    bw.close();

                }

            } catch (Exception e) {
                e.printStackTrace();

            }

        }

    }

    @ApiOperation("公众号页面导出测试记录")
    @GetMapping(value = "/export_view")
    public ResponseBaseEntity export(String examResult_id) throws IOException {
        ResponseBaseEntity response = new ResponseBaseEntity();
        if (examResult_id == null || "".equals(examResult_id)) {
            response.setBody(null);
        }
        ExamResultDto erd = examResultService.findById(Integer.parseInt(examResult_id));
        if (erd.getEchart_pho() == null || "".equals(erd.getEchart_pho())) {
            response.setBody(null);
        } else {
            response.setBody(examResultService.export_view(erd.getEchart_pho()));
        }
        return response;
    }

    @ApiOperation("测试报告查询广告")
    @GetMapping(value = "/query_advert")
    public ResponseBaseEntity query_advert() throws IOException {
        ResponseBaseEntity response = new ResponseBaseEntity();
        //查询系统广告
        List<AdvertDto> advertPd = advertService.queryAll(null);
        if (!org.springframework.util.CollectionUtils.isEmpty(advertPd)) {
            List<AdvertDto> advertList = advertPd.stream().filter(s -> s.getStatus().equals("0") && "0".equals(s.getType())).collect(Collectors.toList());
            if (!org.springframework.util.CollectionUtils.isEmpty(advertList)) {
                response.setBody(advertList);
            }
        }
        return response;
    }

    @ApiOperation("测试报告查询接口")
    @GetMapping(value = "/query_report")
    public ResponseBaseEntity query_report(String mobiles) throws Exception {
        ResponseBaseEntity response = new ResponseBaseEntity();
        if (mobiles == null || "".equals(mobiles)) {
            response.setBody(null);
        }
        Map<String, List<String>> reportMaps = new HashMap<>();
        String[] mobilesArr = mobiles.split(",");
        for (String moblie : mobilesArr) {
            List<WxUser> users = wxUserService.findByMoblie(moblie);
            String[] openIds = new String[users.size()];
            for (int i = 0; i < users.size(); i++) {
                WxUser wxUser = users.get(i);
                openIds[i] = wxUser.getOpenId();
//                if(wxUser != null && wxUser.getOpenId() != null && !"".equals(wxUser.getOpenId()))
//                {
//                    if(i == 0)
//                    {
//                        openIds += ","+wxUser.getOpenId()+"'";
//                    }
//                    else if(i == users.size()-1)
//                    {
//                        openIds += ",'"+wxUser.getOpenId();
//                    }
//                    else
//                    {
//                        openIds += ",'"+wxUser.getOpenId()+"'";
//                    }
//                }
            }
            if (!"".equals(openIds)) {
                List<String> reportUrl = new ArrayList<>();
                List<ExamResult> examResults = examResultService.findByOpenId(openIds);
                if (examResults != null && examResults.size() > 0) {
                    for (ExamResult er : examResults) {
                        reportUrl.add("http://wx.drzh-atmr.cn" + er.getReportUrl());
                    }
                }
                reportMaps.put(moblie, reportUrl);
            }

        }
        response.setBody(reportMaps);
        return response;
    }

    public static void main(String[] args) {
        String syncUrl = "http://enterprise.drzh-atmr.cn/api/examResult/receive";
        AtmrTestResultRespDTO resultRespDTO = new AtmrTestResultRespDTO();
        resultRespDTO.setEntCode("RKJ8MHlX+AU9EA3Q5Ii6Kw==");
        resultRespDTO.setExamResult("28.0,31.0,26.0,21.0");
        resultRespDTO.setAtmrResultType("T,A,M,R");
        String result = HttpUtils.post(syncUrl, JSON.toJSONString(resultRespDTO));
        System.out.println(result);
    }
}
